import log from '../../../helpers/logger';
import { pushDiscordWebhook } from '../../../helpers/pushDiscordWebhook';
//import { validateLink } from '../../../helpers/dataValidation';
import {
  getPermissionsTree,
  refreshDbMenus,
  getUserPermissionsTree,
  refreshRoutes,
  getGroupPermissionsTree,
  getCheckedGroupPermissionsId
} from '../../../services/uctoo/permissions';
import {
  authorizedRouteHandler,
  ControllerMethodTypes,
  defaultRouteHandler,
} from '../../../../interfaces';
import { Request } from 'hyper-express';
import { showSelectedObjectKeys } from '../../../helpers/utilsJS';
import { permissions } from '../../../../../prisma/generated/uctoo';
import { setExCache } from '../../../helpers/redis';
import app from '../../../../app'
  //#region AutoCreateCode
import {
  createPermissions,
  deletePermissionsFromDatabase,
  deleteMultiPermissionsFromDatabase,
  editPermissionsInDatabase,
  editMultiPermissionsInDatabase,
  getPermissionsFromDatabase,
  getPermissionssFromDatabase,
  queryPermissionssFromDatabase,
  countPermissionss
} from '../../../services/uctoo/permissions';

class uctooPermissionsController {

  protected validateAndDestructureBody = async (
    req: Request,
    userId: string,
    actionType: ControllerMethodTypes
  ) => {
    const body = await req.json();
    const keysArray = Object.keys(body);       //如需自定义控制接收字段可在此定义，如['id','link','privacy_level','owner','description','group_id','stars'] ，默认接收所有提交字段
    const uctooPermissions = showSelectedObjectKeys(body, keysArray) as permissions;
    uctooPermissions.creator = userId;

    return uctooPermissions;
  };
  public add: authorizedRouteHandler = async (req, res) => {
    try {
      const user = res.locals.id.user;
      const uctooPermissions = await this.validateAndDestructureBody(
        req,
        user,
        ControllerMethodTypes.ADD
      );
      if (!uctooPermissions) return res.status(400).json({ errno: "40001", errmsg: '提交数据格式错误' });

      const createdPermissions = await createPermissions(uctooPermissions);
      if (!createdPermissions) return res.status(500).json({ errno: "50001", errmsg: "database query failed" });

      res.status(200).json(createdPermissions);
    } catch (e) {
      log.error({ errno: "50000", errmsg: e.message, desc: e });
      return res.status(500).json({ errno: "50000", errmsg: e.message });
    }
  };
  public edit: authorizedRouteHandler = async (req, res) => {
    try {
      const user = res.locals.id.user;
      const body = await req.json();
      const { id,ids,force } = body;

      if(ids){
        const uctooPermissions = await this.validateAndDestructureBody(
          req,
          user,
          ControllerMethodTypes.EDIT
        );
        if (!uctooPermissions) return res.status(400).json({ errno: "40001", errmsg: '提交数据格式错误' });

        const editedPermissions = await editMultiPermissionsInDatabase(uctooPermissions, JSON.parse(ids), user);
        
        if (typeof editedPermissions === 'object' && 'success' in editedPermissions) {
          if (!editedPermissions.success) {
            return res.status(403).json({
              errno: "40301", 
              errmsg: editedPermissions.reason,
              ...(editedPermissions.permissionsId && { permissionsId: editedPermissions.permissionsId })
            });
          }
          return res.status(200).json(editedPermissions.data);
        }
        
        res.status(200).json(editedPermissions);
      }else{
        const uctooPermissions = await this.validateAndDestructureBody(
          req,
          user,
          ControllerMethodTypes.EDIT
        );
        if (!uctooPermissions) return res.status(400).json({ errno: "40001", errmsg: '提交数据格式错误' });

        const editedPermissions = await editPermissionsInDatabase(uctooPermissions, uctooPermissions.id, user);
        
        if (typeof editedPermissions === 'object' && 'success' in editedPermissions) {
          if (!editedPermissions.success) {
            return res.status(403).json({ errno: "40301", errmsg: editedPermissions.reason });
          }
          return res.status(200).json(editedPermissions.data);
        }
        res.status(200).json(editedPermissions);
      }      
    } catch (e) {
      log.error({ errno: "50000", errmsg: e.message, desc: e });
      return res.status(500).json({ errno: "50000", errmsg: e.message });
    }
  };
  public delete: authorizedRouteHandler = async (req, res) => {
    try {
      const body = await req.json();
      const { id,ids,force } = body;
      const user = res.locals.id.user;

      if(ids){
        const deletionResult = await deleteMultiPermissionsFromDatabase(JSON.parse(ids), force, user);
        
        if (typeof deletionResult === 'object' && 'success' in deletionResult) {
          if (!deletionResult.success) {
            return res.status(403).json({
              errno: "40301", 
              errmsg: deletionResult.reason,
              ...(deletionResult.permissionsId && { permissionsId: deletionResult.permissionsId })
            });
          }
          return res.status(200).json({ desc: '删除成功' });
        }
        
      }else{
        const deletionResult = await deletePermissionsFromDatabase(id, force, user);
        
        if (typeof deletionResult === 'object' && 'success' in deletionResult) {
          if (!deletionResult.success) {
            return res.status(403).json({ errno: "40301", errmsg: deletionResult.reason });
          }
          return res.status(200).json({ desc: '删除成功' });
        }
        
      }

      res.status(200).json({ desc: '删除成功' });
    } catch (e) {
      log.error({ errno: "50000", errmsg: e.message, desc: e });
      return res.status(500).json({ errno: "50000", errmsg: e.message });
    }
  };
  public getSingle: authorizedRouteHandler = async (req, res) => {
    try {
      const { id } = req.params;
      const user = res.locals.id.user;

      const permissionsFromDb = await getPermissionsFromDatabase(id, user);
      if (!permissionsFromDb) {
        return res.status(404).json({ 
          errno: "40401", 
          errmsg: '未找到该实体或您没有权限访问' 
        });
      }

      res.status(200).json(permissionsFromDb);
    } catch (e) {
      log.error({ errno: "50000", errmsg: e.message, desc: e });
      return res.status(500).json({ errno: "50000", errmsg: e.message });
    }
  };
  public getMany: authorizedRouteHandler = async (req, res) => {
    try {
      const limit = parseInt(req.params.limit);
      const page = parseInt(req.params.page) || 0;
      const skip = parseInt(req.params.skip) || 0;
      const query = req.query;
      
      if (limit > 100) return res.status(400).json({ errno: "40002", errmsg: '请求数量不能超过100条' });
      if (isNaN(limit)) return res.status(400).json({ errno: "40003", errmsg: '请求数量必须是数字' });
      
      const user = res.locals.id.user;
      const totalCount = await countPermissionss(user);
      
      if (query) {
        const permissionssFromDb = await queryPermissionssFromDatabase(limit, page, skip, query, user);
        if (!permissionssFromDb) return res.status(404).json({ errno: "40401", errmsg: '未找到符合条件的实体' });

        res.status(200).json({
          currentPage: page,
          totalCount: totalCount,
          totalPage: Math.ceil(Number(totalCount)/limit),
          permissionss: permissionssFromDb
        });
      } else {
        const permissionssFromDb = await getPermissionssFromDatabase(limit, skip, page, user);
        if (!permissionssFromDb) return res.status(404).json({ errno: "40401", errmsg: '未找到符合条件的实体' });

        res.status(200).json({
          currentPage: page,
          totalCount:totalCount,
          totalPage: Math.ceil(Number(totalCount)/limit),
          permissionss: permissionssFromDb
        });
      }


    } catch (e) {
      log.error({ errno: "50000", errmsg: e.message, desc: e });
      return res.status(500).json({ errno: "50000", errmsg: e.message });
    }
  };
  //#endregion AutoCreateCode

  public menuAll: defaultRouteHandler = async (req, res) => {
    try {

      const permissionssFromDb = await getPermissionsTree();
      res.status(200).json(permissionssFromDb);
   
    } catch (e) {
      log.error({ err: e.message, desc: e });
      return res.status(500).json({ err: e.message, desc: e });
    }
  };

  /**
   * 请求body中参数有id则查询id用户的权限树。没有id参数则查询token所属用户的权限树
   * @param req 
   * @param res 
   * @returns 
   */
  public getUserPermissions: defaultRouteHandler = async (req, res) => {
    if (res.locals && res.locals.id && res.locals.id.user){
      try {
      
      const body = await req.json();
      const user = body.id ? body.id : res.locals.id.user;     //如果提交数据中包含id则返回用户id的权限，否则返回当前登录用户权限
      log.info({ userinfo: user });
      const permissionssFromDb = await getUserPermissionsTree(user); 
      res.status(200).json(permissionssFromDb);
            
    } catch (e) {
      log.error({ err: e.message, desc: e });
      return res.status(500).json({ err: e.message, desc: e });
    }
    }else{     
      return res.status(401).json([]);   //401登录过期，前端需再登录
    }
  };

  public loadMenuFromDb: defaultRouteHandler = async (req, res) => {
    try {
      const dbMenus = await refreshDbMenus();
      res.status(200).json(dbMenus);
     
    } catch (e) {
      log.error({ err: e.message, desc: e });
      return res.status(500).json({ err: e.message, desc: e });
    }
  };

  public loadRouteFromApp: defaultRouteHandler = async (req, res) => {
    try {
      const appRoutes = await refreshRoutes();
      res.status(200).json(appRoutes);
     
    } catch (e) {
      log.error({ err: e.message, desc: e });
      return res.status(500).json({ err: e.message, desc: e });
    }
  };

    /**
   * 通过body中参数 组id查询组的权限树。
   * @param req 
   * @param res 
   * @returns 
   */
    public getGroupPermissions: defaultRouteHandler = async (req, res) => {
      if (res.locals && res.locals.id && res.locals.id.user){
        try {
        
        const body = await req.json();
        const group_id = body.id;    
        log.info({ userinfo: group_id });
        const permissionssFromDb = await getGroupPermissionsTree(group_id); 
        res.status(200).json(permissionssFromDb);
              
      } catch (e) {
        log.error({ err: e.message, desc: e });
        return res.status(500).json({ err: e.message, desc: e });
      }
      }else{     
        return res.status(401).json([]);   //401登录过期，前端需再登录
      }
    };
  
    /**
   * 通过body中参数 组id查询组的权限树。
   * @param req 
   * @param res 
   * @returns 
   */
    public  getCheckedGroupPermissions: defaultRouteHandler = async (req, res) => {
      if (res.locals && res.locals.id && res.locals.id.user){
        try {
        
        const body = await req.json();
        const group_id = body.id;    
        log.info({ userinfo: group_id });
        const permissionssFromDb = await getCheckedGroupPermissionsId(group_id); 
        res.status(200).json(permissionssFromDb);
              
      } catch (e) {
        log.error({ err: e.message, desc: e });
        return res.status(500).json({ err: e.message, desc: e });
      }
      }else{     
        return res.status(401).json([]);   //401登录过期，前端需再登录
      }
    };
}

export default uctooPermissionsController;
